package com.wangcang.widgetlibrary.recording;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.dialog.DialogTools;
import com.wangcang.widgetlibrary.tools.FileUtils;
import com.wangcang.widgetlibrary.tools.PermissionUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.wangcang.widgetlibrary.R.id.rb_record_start;

public class RecordingActivity extends AppCompatActivity implements View.OnClickListener, PermissionUtils.PermissionCallbacks, DialogTools.ConfirmListener {
    private static final int HANDLER_RECORD = 200;
    //最大录制时间
    private              int maxDuration    = 180000;
    private long           liveTime;//倒计时的时间
    private RecordedButton mRbStart;//转圈的控件

    private RecordArmUtils mRecordArmUtils;
    private ArrayList         mRecordFileList;//录音的集合
    private MediaRecorder     mMediaRecorder;
    private Button            mBtQuit;
    private Button            mBtSure;
    private TextView          mTvTimer;
    private long              mStartTime;
    private ImageView         mImAnim;
    private AnimationDrawable mAnimationDrawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recodeing);
        initView();
        PermissionUtils.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, 1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        /**
         * 当requestcode相同时候，同时perms.size == 请求的权限数时候，认为权限请求成功。
         */
        if (requestCode == 1 && perms.size() == 2) {
            //权限全部获得 进行录音操作
            initData();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        /**
         * 调用了一次拒绝权限认为失败
         */
        if (requestCode == 1) {
            PermissionUtils.permissionDialog(this, perms, null);
        }
    }

    private void initView() {
        mImAnim = (ImageView) findViewById(R.id.im_record_anim);
        mAnimationDrawable = (AnimationDrawable) mImAnim.getDrawable();
        startAnim();
        mRbStart = (RecordedButton) findViewById(rb_record_start);//动画按钮
        mBtQuit = (Button) findViewById(R.id.bt_record_quit);//取消按钮
        mBtQuit.setOnClickListener(this);
        mBtSure = (Button) findViewById(R.id.bt_record_finish);//完成按钮
        mBtSure.setOnClickListener(this);
        mTvTimer = (TextView) findViewById(R.id.tv_record_time);//显示时间
    }

    private void initData() {
        //原型画圈计时
        startDrawTime();
        //显示时间计时器
        startTimer();
        //开始录音
        startRecord();
    }

    public void startDrawTime() {
        //得到刚进来的最原始时间
        mStartTime = System.currentTimeMillis();
        handlerAnim.sendEmptyMessageDelayed(HANDLER_RECORD, 0);
        //设置录音默认的最大时常
        mRbStart.setMax(maxDuration);
        mRbStart.setOnGestureListener(new RecordedButton.OnGestureListener() {
            @Override
            public void onLongClick() {
                //                mRbStart.setSplit();
                //                myHandler.sendEmptyMessageDelayed(HANDLER_RECORD, 100);

            }

            @Override
            public void onClick() {

            }

            @Override
            public void onLift() {

            }

            @Override
            public void onOver() {

            }
        });
    }

    //开始计时功能
    private void startTimer() {
        //        Calendar calendar = Calendar.getInstance();
        //        calendar.setTimeInMillis(0);
        //        calendar.add(Calendar.HOUR_OF_DAY, -8);
        //        Date time = calendar.getTime();
        liveTime = 180000;
        handlerAnim.post(timerRunnable);
    }

    public void startRecord() {
        mMediaRecorder = new MediaRecorder();
        mRecordFileList = new ArrayList();//录音的集合
        mRecordArmUtils = new RecordArmUtils(this, mMediaRecorder);
        //取得SD Card 获得WangCangResson文件夹下.mp3后缀的 文件名集合mRecordFileList
        getRecordFiles();
        //开始录音
        mRecordArmUtils.recordVolume(mRecordFileList);
    }

    private int     pos         = -1;
    private File    myPlayFile  = null;
    private boolean isRecording = true;
    @Override
    public void onClick(View v) {
        int i = v.getId();
        stopRecordEvent();
        if (i == R.id.bt_record_quit) {//停止录音
            showDialog();
        } else if (i == R.id.bt_record_finish) {//保存录音
            String recordingFile = "";
            if(mRecordFileList!=null && mRecordFileList.size()>0){
                recordingFile = (String)mRecordFileList.get(mRecordFileList.size()-1);
            }

            Bundle bundle = new Bundle();
            bundle.putString("filepath",recordingFile);

            Intent intent=new Intent();
            intent.putExtras(bundle);
            setResult(1000, intent);

            finish();
        }
    }

    private void stopRecordEvent() {
        isRecording = false;
        //这个变量用来结束录音之后换一张图片
        mRbStart.isStop = true;
        mRecordArmUtils.stopRecordVolume();



        //结束动画
        stopAnim();
        //隐藏动画的图片
        mImAnim.setVisibility(View.INVISIBLE);
        //最新录音对应的集合id
        pos = mRecordFileList.size() - 1;
        myPlayFile = new FileUtils().getRecordsFile(mRecordFileList.get(pos).toString());
        handlerAnim.removeCallbacks(timerRunnable);
    }

    public void showDialog() {
        DialogTools.getInstance().showCustomDialogPrompt(RecordingActivity.this,"Tip", "你确定要取消录音吗？", false, this);
    }

    @Override
    public void setConfirmListener(Dialog dialog, View view, String input) {
        //删除该条录音 结束界面
        mRecordFileList.remove(pos);
        if (myPlayFile.exists()) {
            myPlayFile.delete();
        }
        finish();
    }
    /**
     * 循环执行线程
     */
    private Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            handlerAnim.postDelayed(timerRunnable, 1000);
            liveTime -= 1000;
            CharSequence sysTimeStr = DateFormat.format("mm:ss", liveTime);
            String time = sysTimeStr.toString();
            String[] temp = null;
            //截取到时间的分秒
            temp = time.split(":");
            Log.d("chenchao", "时间" + sysTimeStr + "分钟" + temp[0] + "秒" + temp[1]);
            mTvTimer.setText(sysTimeStr);
            if (liveTime == 0) {
                //设定的录音时间到达
                handlerAnim.removeCallbacks(timerRunnable);
                mTvTimer.setTextColor(getResources().getColor(R.color.common_color_c8_d5d7dc));
                mRbStart.isStop = true;
                mImAnim.setVisibility(View.INVISIBLE);
            }
        }
    };


    private Handler handlerAnim = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_RECORD://动画handler
                    long currentTimeMillis = System.currentTimeMillis();
                    long durTime = currentTimeMillis - mStartTime;
                    mRbStart.setProgress(durTime);
                    if (isRecording) {
                        handlerAnim.sendEmptyMessageDelayed(HANDLER_RECORD, 0);
                    }
                    break;
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            stopRecordEvent();
            showDialog();
        }
        return true;
    }

    public void startAnim() {
        mAnimationDrawable.start();
    }

    public void stopAnim() {
        mAnimationDrawable.stop();
    }

    public void getRecordFiles() {
        /* 判断SD Card是否插入 */
        boolean sdCardExit = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        /* 取得SD Card路径作为录音的文件位置 */
        if (sdCardExit) {
            File dir = new FileUtils().getRecordPath();
            File files[] = dir.listFiles();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().indexOf(".") >= 0) {
                        // 只取.mp3文件,  files[i].getName().indexOf(".")读取"."的位置，然后取得"."(包括.)以后的字符串
                        String fileS = files[i].getName().substring(
                                files[i].getName().indexOf("."));
                        if (fileS.toLowerCase().equals(".mp3")) {
                            mRecordFileList.add(files[i].getName());
                        }
                    }
                }
            }
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerAnim = null;
    }


}
